/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package smartgym.gui;

import java.awt.Component;
import java.sql.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManagerFactory;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import smartgym.controllers.PaymentJpaController;
import smartgym.controllers.exceptions.NonexistentEntityException;
import smartgym.gui.tables.FinancePaymentTable;
import smartgym.models.entities.Client;
import smartgym.models.entities.Employee;
import smartgym.models.entities.Payment;

/**
 *
 * @author Sammy Guergachi <sguergachi at gmail.com>
 */
public class FinanceClientWindow extends javax.swing.JDialog {

    FinancePaymentTable inadiplentTable, pedenceTable;
    PaymentJpaController paymentController;
    Client client;
    Employee employee;

    /**
     * Creates new form Financeiro
     */
    public FinanceClientWindow(JFrame parent, boolean modal, EntityManagerFactory entityManagerFactory, Employee employee) {
        super(parent, modal);
        initComponents();
        this.employee = employee;
        paymentController = new PaymentJpaController(entityManagerFactory);
        inadiplentTable = new FinancePaymentTable();
        pedenceTable = new FinancePaymentTable();
        pedenceFrame.add(pedenceTable);
        inadiplentFrame.add(inadiplentTable);


    }

    public void restart() {
        if (client != null) {
            inadiplentTable.setObjectList(paymentController.findPaymentInadiplentByClient(client));
            pedenceTable.setObjectList(paymentController.findPaymentPendenceByClient(client));
        } else {
            JOptionPane.showMessageDialog(this, "Não há client disponivel para esta janela");
            this.dispose();
        }

    }

    public void setClient(Client client) {
        this.client = client;
        restart();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        pedenceFrame = new javax.swing.JPanel();
        inadiplentFrame = new javax.swing.JPanel();
        alunoStatusLabel = new javax.swing.JLabel();
        ValidButton = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JSeparator();
        disregardButton = new javax.swing.JButton();
        PayButton = new javax.swing.JButton();

        jLabel1.setText("Receita Atual:");

        jLabel2.setText("Deve:");

        jLabel3.setText("<valor >");

        jLabel4.setText("<valor>");

        pedenceFrame.setBorder(javax.swing.BorderFactory.createTitledBorder("Pedente de Confirmação"));
        pedenceFrame.setLayout(new java.awt.BorderLayout());

        inadiplentFrame.setBorder(javax.swing.BorderFactory.createTitledBorder("Atrazados"));
        inadiplentFrame.setLayout(new java.awt.BorderLayout());

        alunoStatusLabel.setText("status");

        ValidButton.setText("Validar");
        ValidButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ValidButtonActionPerformed(evt);
            }
        });

        jButton2.setText("Sair");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        disregardButton.setText("Descon");
        disregardButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                disregardButtonActionPerformed(evt);
            }
        });

        PayButton.setText("Receber");
        PayButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                PayButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(alunoStatusLabel))
                    .addComponent(jSeparator2)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel4))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(12, 12, 12)
                                .addComponent(ValidButton))
                            .addComponent(pedenceFrame, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(jButton2)
                                .addGap(8, 8, 8))
                            .addComponent(inadiplentFrame, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addComponent(PayButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(disregardButton)
                                .addGap(0, 77, Short.MAX_VALUE)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel3)
                    .addComponent(alunoStatusLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(pedenceFrame, javax.swing.GroupLayout.DEFAULT_SIZE, 213, Short.MAX_VALUE)
                    .addComponent(inadiplentFrame, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ValidButton)
                    .addComponent(disregardButton)
                    .addComponent(PayButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void disregardButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_disregardButtonActionPerformed
        // TODO add your handling code here:
        Payment payment = (Payment) inadiplentTable.getSelectRow();

        if (payment == null) {
            JOptionPane.showMessageDialog(this, "Nenhuma linha selecionada");
            return;
        }
        int resp = JOptionPane.showConfirmDialog(this, "Deseja desconciderar o pagamento?", "Confirme", JOptionPane.YES_NO_OPTION);
        if (resp == JOptionPane.YES_OPTION) {
            disregard(payment);
        }
    }//GEN-LAST:event_disregardButtonActionPerformed

    private void PayButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PayButtonActionPerformed
        // TODO add your handling code here:
        Payment payment = (Payment) inadiplentTable.getSelectRow();

        if (payment == null) {
            JOptionPane.showMessageDialog(this, "Nenhuma linha selecionada");
            return;
        }
        int resp = JOptionPane.showConfirmDialog(this, "Deseja validar o pagamento?", "Confirme", JOptionPane.YES_NO_OPTION);
        if (resp == JOptionPane.YES_OPTION) {
            pay(payment);
        }
    }//GEN-LAST:event_PayButtonActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        cancel();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void ValidButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ValidButtonActionPerformed
        // TODO add your handling code here:
        Payment payment = (Payment) pedenceTable.getSelectRow();

        if (payment == null) {
            JOptionPane.showMessageDialog(this, "Nenhuma linha selecionada");
            return;
        }
        int resp = JOptionPane.showConfirmDialog(this, "Deseja validar o pagamento?", "Confirme", JOptionPane.YES_NO_OPTION);
        if (resp == JOptionPane.YES_OPTION) {
            valid(payment);
        }
    }//GEN-LAST:event_ValidButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FinanceClientWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FinanceClientWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FinanceClientWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FinanceClientWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                //new FinanceClientWindow().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton PayButton;
    private javax.swing.JButton ValidButton;
    private javax.swing.JLabel alunoStatusLabel;
    private javax.swing.JButton disregardButton;
    private javax.swing.JPanel inadiplentFrame;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JPanel pedenceFrame;
    // End of variables declaration//GEN-END:variables

    private void cancel() {
        int resp = JOptionPane.showConfirmDialog(this, "Tem certeza que deseja cancelar?", "Sair", JOptionPane.YES_NO_OPTION);

        if (resp == JOptionPane.YES_OPTION) {
            this.dispose();
            
        }
    }

    private void valid(Payment payment) {
        payment.setValid(true);
        try {
            paymentController.edit(payment);            
        } catch (NonexistentEntityException ex) {
            Logger.getLogger(FinanceClientWindow.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(FinanceClientWindow.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            JOptionPane.showMessageDialog(this, "Pagamento validado com sucesso.");
            restart();
        }
    }

    private void disregard(Payment payment) {
        payment.setValid(true);
        try {
            paymentController.edit(payment);            
        } catch (NonexistentEntityException ex) {
            Logger.getLogger(FinanceClientWindow.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(FinanceClientWindow.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            JOptionPane.showMessageDialog(this, "Pagamento validado com sucesso.");
            restart();
        }
    }

    private void pay(Payment payment) {
        payment.setEmployee(employee);
        payment.setPaid(true);
        java.util.Date date = new java.util.Date();
        payment.setPaymentedDay(new Date(date.getTime()));
        try {
            paymentController.edit(payment);            
        } catch (NonexistentEntityException ex) {
            Logger.getLogger(PaymentWindow.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(PaymentWindow.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            JOptionPane.showMessageDialog(this, "Pagamento resgistrado com sucesso.");
            restart();
        }
    }
}
